package com.jamaskii.ecdict;

import com.jamaskii.utils.IOUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class PronunciationStream {
    private String path;

    public PronunciationStream(String pronunciationPath){
        this.path=pronunciationPath;
    }

    public String getPronunciation(Word word, int type){
        return getPronunciation(word,path,null,type);
    }

    public String getPronunciation(Word word,String pronPath,String meaning,int type){
        if(meaning==null){
            String filName;
            if(type==0||word.chinese){
                filName=pronPath+"/US/"+word.hashCode()+".m4a";
            }else {
                filName=pronPath+"/GB/"+word.hashCode()+".m4a";
            }
            File objFile=new File(filName);
            if(objFile.exists()){
                return objFile.getAbsolutePath();
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    public boolean downloadPronunciation(Word word, int type){
        byte[] data;
        //中文无需重复下载
        if(word.chinese&&type!=0) return true;
        try{
            URL url;
            String encWord;
            if(word.chinese){
                encWord = URLEncoder.encode(String.format("%s。组词：%s",word.name,word.translated),"utf-8");
            }else {
                encWord = URLEncoder.encode(word.name,"utf-8");
            }
            if(!word.chinese) {
                url = new URL("http://dict.youdao.com/dictvoice?type=" + type + "&audio=" + encWord);
            }else {
                url = new URL("https://fanyi.baidu.com/gettts?lan=zh&text="+ encWord +"&spd=5&source=web");
            }
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            if (word.chinese) {
                connection.addRequestProperty("Accept-Encoding","identity;q=1, *;q=0");
                connection.addRequestProperty("Range","bytes=0-");
                connection.addRequestProperty("Referer","https://fanyi.baidu.com/");
                connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.112 Safari/537.36");
            }
            data= IOUtils.readBytes(connection.getInputStream());
            String fileName="";
            if(type==0){
                fileName=path+"/US/" + word.hashCode() + ".m4a";
            }
            else if(type==1){
                fileName=path+"/GB/" + word.hashCode() + ".m4a";
            }
            return IOUtils.fileWriteBytes(fileName,data);
        }catch (MalformedURLException e){
            return false;
        }catch (IOException e){
            return false;
        }
    }

}
